﻿using AntdUI;
using PosClient.View;
using PosClient.ViewModel;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PosClient.View
{
    public partial class PresentView : Window, IViewFor<PresentViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (PresentViewModel)value;
        }
        public PresentViewModel ViewModel { get; set; }
        public PresentView()
        {
            InitializeComponent();
            InitBinding();
            InitEvent();
        }

        private void InitBinding()
        {
            ViewModel = new PresentViewModel();
            this.WhenActivated(d =>
            {
                this.Events().Load
                    .Do(x => ActiveControl = input_code)

                    .Subscribe()
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.PluName,
                    v => v.label_name.Text).DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.PluCode,
                    v => v.input_code.Text).DisposeWith(d);

                this.input_code.Events()
                    .KeyDown.Where(x => x.KeyData == Keys.Enter)
                    .Do(y => 
                    {
                        ViewModel.GetGoodCommand.Execute().Subscribe(x =>
                        {
                            if (x.Success)
                            {
                                ViewModel.PluName = x.Data.PluName;
                                ViewModel.Plu = x.Data;
                                ViewModel.ParentViewModel.MathUpdateCommand.Execute(x.Data).Subscribe();
                                pageHeader_title.SubText = "赠送成功，请按Esc退出或继续添加赠送";
                            }
                            else
                            {
                                ViewModel.PluName = $"无此编码{ViewModel.PluCode}";
                                ViewModel.Plu = new Model.Plu();
                            }
                            ActiveControl = input_code;
                            input_code.SelectAll();
                        });
                    })
                    .Subscribe()
                    .DisposeWith(d);

            });
        }

        private void InitEvent()
        {
            this.KeyDown += (s, e) =>
            {
                if (e.KeyData == Keys.Escape)
                {
                    this.Close();
                }
            };
        }
    }
}
